# -*- coding: utf-8 -*-

'''
Created on 2010-3-22

@author: Sameway
'''

import wsgiref.handlers

from django.core.exceptions import SuspiciousOperation

# Google App Engine imports.
from google.appengine.ext.webapp import template, \
    WSGIApplication, RequestHandler
from google.appengine.api import users
from google.appengine.api.users import User

import base64, md5
import time

from model import localUser

class servceBase(RequestHandler):
    user = None

    def initialize(self, request, response):
        RequestHandler.initialize(self, request, response)
        self.getUser()

    def getUser(self):
        userId = self.request.cookies['login_user']
        pwdToken = self.request.cookies['password']
        requestTime = self.request.cookies['time']
       
        sessionData = self.request.cookies['sessionData']
        if userId & pwdToken & requestTime & sessionData:
            valid = base64.decodestring(sessionData)
            if md5.new(userId + pwdToken + requestTime + ' blam blam is soo col').hexdigest() != valid:
                raise SuspiciousOperation, "User tampered with session cookie."
            else:
                theUser = localUser.all().filter('userId = ', userId).get()
                if theUser.passwordToken != pwdToken:
                    raise SuspiciousOperation, "User password error."

        self.user = theUser
            
class login(RequestHandler):
    def get(self, userId, passwordToken, url):
        self.response.headers['Set-Cookies'] = cookies;
        self.redirect(url, None)
        pass

class getAllTask(servceBase):
    def get(self, userId):
        self.response.headers['Content-Type'] = 'html'
        self.response.out.write('hello ' + userId)


def main():
    #template.register_template_library('filter')
    application = WSGIApplication(
                    [('/s/(.*)/tasks',getAllTask),
                     ],debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()